﻿var holder = document.getElementById('holder_file'),
    tests = {
        filereader: typeof FileReader != 'undefined',
        dnd: 'draggable' in document.createElement('span'),
        formdata: !!window.FormData,
        progress: "upload" in new XMLHttpRequest
    },
    support = {
        filereader: document.getElementById('filereader'),
        formdata: document.getElementById('formdata'),
        progress: document.getElementById('progress')
    },
    acceptedTypes = {
        'image/png': true,
        'image/jpeg': true,
        'image/gif': true
    },
    progress = document.getElementById('uploadprogress'),
    progress_cont = document.getElementById('uploadprogress_cont'),
    holder_info = document.getElementById('holder_info'),
    fileupload = document.getElementById('upload'),
    upload_info = document.getElementById('upload_info'),
    dad_not_supported_label = document.getElementById('dad_not_supported_label');

function previewfile(file) {
    /*if (tests.filereader === true && acceptedTypes[file.type] === true) {
        var reader = new FileReader();
        reader.onload = function (event) {
            var image = new Image();
            image.src = event.target.result;
            image.width = 250; // a fake resize
            holder.appendChild(image);
        };

        reader.readAsDataURL(file);
    } else {*/
    holder_info.className = 'hidden';
    if (isOneFile == '1') {
        upload_info.innerHTML = '';
    }
    upload_info.innerHTML += '<p>' + file.name + ' ' + (file.size ? '(' + (file.size / 1024).toFixed(1) + ' Кб)' : '') + '</p>';
    console.log(file);
    //}
}

function readfiles(files) {
    var formData = tests.formdata ? new FormData() : null;
    for (var i = 0; i < files.length; i++) {
        if (tests.formdata)
            formData.append('file', files[i]);
        previewfile(files[i]);
    }

    // now post a new XHR request
    if (tests.formdata) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', uploadUrl);
        xhr.onload = function (data) {
            progress.value = progress.innerHTML = 100;
            progress_cont.className = 'hidden';
        };
        
        if (tests.progress) {
            xhr.upload.onprogress = function (event) {
                if (event.lengthComputable) {
                    var complete = (event.loaded / event.total * 100 | 0);
                    progress.value = progress.innerHTML = complete;
                    progress_cont.className = '';
                }
            };
        }

        xhr.send(formData);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                $("#upload_result").val(xhr.responseText);
                $("#upload_result").change();
            }
        };
    };
}

if (holder != null) {
    "filereader formdata progress".split(' ').forEach(function (api) {
        if (tests[api] === false) {
            support[api].className = 'fail';
        } else {
            // FFS. I could have done el.hidden = true, but IE doesn't support
            // hidden, so I tried to create a polyfill that would extend the
            // Element.prototype, but then IE10 doesn't even give me access
            // to the Element object. Brilliant.
            support[api].className = 'hidden';
        }
    });

    fileupload.querySelector('input').onchange = function () {
        readfiles(this.files);
    };

    if (tests.dnd) {
        holder.ondragover = function () { this.className = 'hover'; return false; };
        holder.ondragend = function () { this.className = ''; return false; };
        holder.ondrop = function (e) {
            this.className = '';
            e.preventDefault();

            if (isOneFile == '1') {
                if (e.dataTransfer.files.length > 1) {
                    alert('Разрешено загружать не более одного файла.');
                }
                else {
                    readfiles(e.dataTransfer.files);
                }
            }
            else {
                readfiles(e.dataTransfer.files);
            }
        }
    } else {
        dad_not_supported_label.className = '';
        holder.className = 'hidden';
        holder_info.className = 'hidden';
    }
}